package org.jeecg.modules.demo.mes.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.mes.entity.MesMaterial;
import org.jeecg.modules.demo.mes.entity.MesMaterialConfigure;
import org.jeecg.modules.demo.mes.service.IMesMaterialConfigureService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.mes.service.IMesMaterialService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 物料配置
 * @Author: jeecg-boot
 * @Date: 2022-10-27
 * @Version: V1.0
 */
@Api(tags = "物料配置")
@RestController
@RequestMapping("/mes/mesMaterialConfigure")
@Slf4j
public class MesMaterialConfigureController extends JeecgController<MesMaterialConfigure, IMesMaterialConfigureService> {
    @Autowired
    private IMesMaterialConfigureService mesMaterialConfigureService;
    @Autowired
    private IMesMaterialService mesMaterialService;

    /**
     * 分页列表查询
     *
     * @param mesMaterialConfigure
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "物料配置-分页列表查询")
    @ApiOperation(value = "物料配置-分页列表查询", notes = "物料配置-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<MesMaterialConfigure>> queryPageList(MesMaterialConfigure mesMaterialConfigure,
                                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                             HttpServletRequest req) {
        QueryWrapper<MesMaterialConfigure> queryWrapper = QueryGenerator.initQueryWrapper(mesMaterialConfigure, req.getParameterMap());
        Page<MesMaterialConfigure> page = new Page<MesMaterialConfigure>(pageNo, pageSize);
        IPage<MesMaterialConfigure> pageList = mesMaterialConfigureService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param mesMaterialConfigure
     * @return
     */
    @AutoLog(value = "物料配置-添加")
    @ApiOperation(value = "物料配置-添加", notes = "物料配置-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_material_configure:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody MesMaterialConfigure mesMaterialConfigure,HttpServletRequest request) {
        //校验【物料编码】不能重复
        checkMaterialCode(mesMaterialConfigure);
        mesMaterialConfigure.setUpdateBy(JwtUtil.getUserNameByToken(request));
        mesMaterialConfigure.setUpdateTime(new Date());
        mesMaterialConfigureService.save(mesMaterialConfigure);
        return Result.OK("添加成功！");
    }

    /**
     * 校验【物料编码】唯一性
     */
    private void checkMaterialCode(MesMaterialConfigure mesMaterialConfigure) {
        final String materialCode = mesMaterialConfigure.getMaterialCode();
        final List<MesMaterialConfigure> list = mesMaterialConfigureService.queryMaterialConfiguresByMaterialCode(materialCode);
        if (list == null || list.size() == 0) {
            return;
        }
        final String exceptionMsg = "物料编码已存在";
        final String id = mesMaterialConfigure.getId();
        if (StringUtils.isBlank(id)) {
            //新增
            throw new JeecgBootException(exceptionMsg);
        }
        //编辑
        if (list.size() > 1) {
            throw new JeecgBootException(exceptionMsg);
        }
        final MesMaterialConfigure configure = list.get(0);
        if (!StringUtils.equals(configure.getId(),id)){
            throw new JeecgBootException(exceptionMsg);
        }
    }

    /**
     * 编辑
     *
     * @param mesMaterialConfigure
     * @return
     */
    @AutoLog(value = "物料配置-编辑")
    @ApiOperation(value = "物料配置-编辑", notes = "物料配置-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_material_configure:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody MesMaterialConfigure mesMaterialConfigure) {
        //校验【物料编码】不能重复
        checkMaterialCode(mesMaterialConfigure);
        mesMaterialConfigureService.updateById(mesMaterialConfigure);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "物料配置-通过id删除")
    @ApiOperation(value = "物料配置-通过id删除", notes = "物料配置-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_material_configure:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        //校验物料配置是否已经使用
        checkMaterialCodeUsed(id);
        mesMaterialConfigureService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 校验物料编码是否被使用了
     */
    private void checkMaterialCodeUsed(String id) {
        final MesMaterialConfigure mesMaterialConfigure = mesMaterialConfigureService.getById(id);
        final String materialCode = mesMaterialConfigure.getMaterialCode();
        final Map<String,Object> cxMap = new HashMap<>();
        cxMap.put("materialCode",materialCode);
        final List<MesMaterial> mesMaterials = mesMaterialService.queryMesMaterialsSelective(cxMap);
        if (mesMaterials!=null && mesMaterials.size()>0){
            throw new JeecgBootException("该物料配置已经被使用了，请勿删除");
        }
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "物料配置-批量删除")
    @ApiOperation(value = "物料配置-批量删除", notes = "物料配置-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_material_configure:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mesMaterialConfigureService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "物料配置-通过id查询")
    @ApiOperation(value = "物料配置-通过id查询", notes = "物料配置-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<MesMaterialConfigure> queryById(@RequestParam(name = "id", required = true) String id) {
        MesMaterialConfigure mesMaterialConfigure = mesMaterialConfigureService.getById(id);
        if (mesMaterialConfigure == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(mesMaterialConfigure);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mesMaterialConfigure
     */
    //@RequiresPermissions("org.jeecg.modules.demo:mes_material_configure:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesMaterialConfigure mesMaterialConfigure) {
        return super.exportXls(request, mesMaterialConfigure, MesMaterialConfigure.class, "物料配置");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("mes_material_configure:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MesMaterialConfigure.class);
    }

}
